package cn.tedu.esspringboot.es;

import cn.tedu.esspringboot.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class StudentSearcher {
    //用来执行查询的工具
    @Autowired
    private ElasticsearchOperations operations;

    public List<Student> searchByBirthDate(String birthDate){
        Criteria criteria = new Criteria("birthDate").is(birthDate);
        return query(criteria,null);
    }

    public List<Student> searchByBirthDate(String ge, String le, Pageable pageable){//分页
        Criteria criteria = new Criteria("birthDate").between(ge,le);
        return query(criteria,pageable);
    }

    private List<Student> query(Criteria criteria,Pageable pageable) {
        CriteriaQuery q = new CriteriaQuery(criteria);
        if(pageable != null){
            q.setPageable(pageable);
        }
        SearchHits<Student> hist = operations.search(q, Student.class);
        List<Student> list = hist.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return list;
    }
}
